package com.opensource.bykc.excel_lianxi.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.opensource.bykc.excel_lianxi.entity.WorkHistory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author wzh
 * @date 2024/9/16
 * @apiNote
 */
@RestController
@RequestMapping("/easyexcel")
public class testControlller_easyexcel {
    //   参考网页
    //https://segmentfault.com/a/1190000038566393

    /**
     * @description EasyExcel导出excel
     * @author wzh
     *
     */
    @GetMapping("/excel")
    public void test(){
        // 生成Excel路径

        String comFilePath = "H:\\project\\study\\面试demo\\机试题\\bykc\\springboot\\src\\main\\resources\\";
        String filePath = comFilePath + "file\\result\\result_01.xlsx";
        String templatePath = comFilePath + "file\\template\\template_01.xlsx";
        ExcelWriter excelWriter = EasyExcel.write(filePath).withTemplate(templatePath).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        // 填充数据
        Map<String, Object> map = new HashMap<>(64);
        map.put("uname", "张三");
        map.put("usex", "男");
        map.put("ubirthday", "2020.10.01");
        map.put("ucardid", "440582xxxxxxxx");
        map.put("umarriage", "未婚");
        map.put("unation", "汉族");
        map.put("unative", "广东xxxx");
        map.put("ubirthplace", "广东xxxx");
        map.put("upolity", "团员");
        map.put("uworktime", "2020.05.15");
        map.put("uhealth", "良好");
        //  插入一级数据
        excelWriter.fill(map, writeSheet);
        //插入二级数据
        excelWriter.fill(new FillWrapper("data1", data1()), fillConfig, writeSheet);
        // 别忘记关闭流
        excelWriter.finish();

        System.out.println("表生成成功！");

    }
    /**
     * @description EasyExcel导出excel的zip文件
     * @author wzh
     *
     */
    //   添加到压缩包
    @GetMapping("/excel_zip")
    public void test(HttpServletRequest request, HttpServletResponse response){
        // 生成Excel路径
        String comFilePath = "H:\\project\\study\\面试demo\\机试题\\bykc\\springboot\\src\\main\\resources\\";
        String filePath = comFilePath + "file\\result\\result_01.xlsx";
        String templatePath = comFilePath + "file\\template\\template_01.xlsx";
        OutputStream outputStream = null;
        ZipOutputStream out = null;
        String zipName = "郭德纲.zip";
        String browser = "";
        response.setContentType("application/octet-stream"); // 设置正确的MIME类型
        browser = request.getHeader("User-Agent");
        try {
            if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
                // IE6, IE7 浏览器
                response.addHeader("content-disposition", "attachment;filename="
                        + new String(zipName.getBytes(), "ISO8859-1"));
            } else if (-1 < browser.indexOf("MSIE 8.0")) {
                // IE8
                response.addHeader("content-disposition", "attachment;filename="
                        + URLEncoder.encode(zipName, "UTF-8"));
            } else if (-1 < browser.indexOf("MSIE 9.0")) {
                // IE9
                response.addHeader("content-disposition", "attachment;filename="
                        + URLEncoder.encode(zipName, "UTF-8"));
            } else if (-1 < browser.indexOf("Chrome")) {
                // 谷歌
                response.addHeader("content-disposition",
                        "attachment;filename*=UTF-8''" + URLEncoder.encode(zipName, "UTF-8"));
            } else if (-1 < browser.indexOf("Safari")) {
                // 苹果
                response.addHeader("content-disposition", "attachment;filename="
                        + new String(zipName.getBytes(), "ISO8859-1"));
            } else {
                // 火狐或者其他的浏览器
                response.addHeader("content-disposition",
                        "attachment;filename*=UTF-8''" + URLEncoder.encode(zipName, "UTF-8"));
            }

            response.setCharacterEncoding("UTF-8");
            outputStream = response.getOutputStream();
            out = new ZipOutputStream(outputStream);
            ByteArrayOutputStream excelByteArrayOutputStream = new ByteArrayOutputStream();
            // 使用 ByteArrayOutputStream 捕获 Excel 输出
            ExcelWriter excelWriter = EasyExcel.write(excelByteArrayOutputStream).withTemplate(templatePath).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            //ExcelWriter excelWriter = EasyExcel.write(filePath).withTemplate(templatePath).build();
            //WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            // 填充数据
            Map<String, Object> map = new HashMap<>(64);
            map.put("uname", "张三");
            map.put("usex", "男");
            map.put("ubirthday", "2020.10.01");
            map.put("ucardid", "440582xxxxxxxx");
            map.put("umarriage", "未婚");
            map.put("unation", "汉族");
            map.put("unative", "广东xxxx");
            map.put("ubirthplace", "广东xxxx");
            map.put("upolity", "团员");
            map.put("uworktime", "2020.05.15");
            map.put("uhealth", "良好");
            //  插入一级数据
            excelWriter.fill(map, writeSheet);
            //插入二级数据
            excelWriter.fill(new FillWrapper("data1", data1()), fillConfig, writeSheet); // 注意：这里可能需要根据实际情况调整
            // 别忘记关闭流
            excelWriter.finish();
            int i = zipName.lastIndexOf(".");
            String fileName = zipName.substring(0,i);
            out.putNextEntry(new ZipEntry(fileName+"/"+"result\\result_01.xlsx"));
            //   下面这两行效果一样，二选一即可
            excelByteArrayOutputStream.writeTo(out);
            //out.write(excelByteArrayOutputStream.toByteArray());
            out.closeEntry();
            System.out.println("表生成成功！");

        }catch (IOException e){
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.finish();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }













    private List<WorkHistory> data1() {
        List<WorkHistory> list = new ArrayList<>();
        WorkHistory workHistory;
        for (int i = 1; i <= 1; i++) {
            workHistory = new WorkHistory();
            workHistory.setUbegintime("2020.05.01");
            //workHistory.setUendtime("2020.05.02");
            //workHistory.setUworkcomp("xxx公司");
            //workHistory.setUworkdesc("后勤");
            list.add(workHistory);
        }
        return list;
    }
}
